//
//  QWConversationsController.m
//  qwm
//
//  Created by kevin on 2023/3/23.
//

#import "QWConversationsController.h"
#import "EMConversationUserDataModel.h"
#import "UserInfoStore.h"
#import "EMNotificationViewController.h"

@interface QWConversationsController ()<EaseConversationsViewControllerDelegate, EMGroupManagerDelegate>
@property (nonatomic, strong) EaseConversationsViewController *easeConvsVC;
@property (nonatomic, strong) EaseConversationViewModel *viewModel;
@end

@implementation QWConversationsController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.isHiddenLeftBarButtonItem = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"消息";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView) name:GROUP_LIST_FETCHFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshConversations)
                                                 name:USER_PUSH_CONFIG_UPDATE object:nil];

    [self _setupSubviews];
    
    if([EMClient sharedClient].isLoggedIn){
        [self refreshConversations];
    }
}
#pragma mark - Subviews
- (void)_setupSubviews
{
    self.viewModel = [[EaseConversationViewModel alloc] init];
    self.viewModel.avatarType = Circular;
    self.viewModel.canRefresh = YES;
    self.viewModel.badgeLabelPosition = EMAvatarTopRight;

    self.easeConvsVC = [[EaseConversationsViewController alloc] initWithModel:self.viewModel];
    self.easeConvsVC.delegate = self;
    [self addChildViewController:self.easeConvsVC];
    [self.view addSubview:self.easeConvsVC.view];
    [self.easeConvsVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(self.view);
    }];
}

- (void)refreshTableView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.easeConvsVC){
            [self.easeConvsVC refreshTable];
        }
    });
}
- (void)refreshConversations {
    [self refreshTableViewWithData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(self.easeConvsVC){
            [self.easeConvsVC refreshTabView];
        }
    });
}

#pragma mark - 环信服务端获取聊天数据
- (void)refreshTableViewWithData
{
//   NSArray *arr =  [[EMClient sharedClient].chatManager getAllConversations];
//    NSLog(@"%@",arr);
    __weak typeof(self) weakself = self;
    [[EMClient sharedClient].chatManager getConversationsFromServer:^(NSArray *aConversations, EMError *aError) {
        if (!aError && [aConversations count] > 0) {
            [weakself.easeConvsVC.dataAry removeAllObjects];
            NSArray<EaseConversationModel *> *modelAry = [self formateConversations:aConversations];
            if (modelAry.count > 0) {
                [weakself.easeConvsVC.dataAry addObjectsFromArray:modelAry];
                [weakself.easeConvsVC refreshTable];
            }
        }
    }];
}
- (NSArray<EaseConversationModel *> *)formateConversations:(NSArray *)conversations
{
    NSMutableArray<EaseConversationModel *> *convs = [NSMutableArray array];
    
    for (EMConversation *conv in conversations) {
        if (!conv.latestMessage) {
            continue;
        }
        
        if (conv.type == EMConversationTypeChatRoom) {
            continue;
        }

        EaseConversationModel *item = [[EaseConversationModel alloc] initWithConversation:conv];
        item.userDelegate = [self easeUserDelegateAtConversationId:conv.conversationId conversationType:conv.type];
        
        [convs addObject:item];
    }
    
    NSArray<EaseConversationModel *> *normalConvList = [convs sortedArrayUsingComparator:
                               ^NSComparisonResult(EaseConversationModel *obj1, EaseConversationModel *obj2)
                               {
        if (obj1.lastestUpdateTime > obj2.lastestUpdateTime) {
            return(NSComparisonResult)NSOrderedAscending;
        }else {
            return(NSComparisonResult)NSOrderedDescending;
        }
    }];
    
    return normalConvList;
}

#pragma mark - EaseConversationsViewControllerDelegate

- (id<EaseUserDelegate>)easeUserDelegateAtConversationId:(NSString *)conversationId conversationType:(EMConversationType)type
{
    EMConversationUserDataModel *userData = [[EMConversationUserDataModel alloc]initWithEaseId:conversationId conversationType:type];
    if(type == EMConversationTypeChat) {
        if (![conversationId isEqualToString:EMSYSTEMNOTIFICATIONID]) {
            EMUserInfo* userInfo = [[UserInfoStore sharedInstance] getUserInfoById:conversationId];
            if(userInfo) {
                if([userInfo.nickname length] > 0) {
                    userData.showName = userInfo.nickname;
                }
                if([userInfo.avatarUrl length] > 0) {
                    userData.avatarURL = userInfo.avatarUrl;
                }
            }else{
                [[UserInfoStore sharedInstance] fetchUserInfosFromServer:@[conversationId]];
            }
        }
    }
    return userData;
}

- (void)easeTableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    EaseConversationCell *cell = (EaseConversationCell*)[tableView cellForRowAtIndexPath:indexPath];
    //系统通知
    if ([cell.model.easeId isEqualToString:EMSYSTEMNOTIFICATIONID]) {
        EMNotificationViewController *controller = [[EMNotificationViewController alloc] initWithStyle:UITableViewStylePlain];
        [self.navigationController pushViewController:controller animated:YES];
        return;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:CHAT_PUSHVIEWCONTROLLER object:cell.model];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
